package com.rectcircle.wechat.util;

import java.util.Iterator;
import java.util.TreeMap;

/**
 * 验证服务器有效性<br>
 * 具体说明见：<a href="http://mp.weixin.qq.com/wiki/8/f9a0b8382e0b77d87b3bcc1ce6fbc104.html#">微信开发文档-接入指南</a>
 * @author RectCircle
 * @version 0.1<br>
 * 2016年7月12日-上午12:12:24<br>
 * Copyright (c) 2016 RectCircle-版权所有<br>
 *
 */
public class ValidService {
	
	
	/**
	 * 验证是否有效<br>
	 * 参数见文档
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @param echostr
	 * @param token
	 * @return 是否验证成功
	 */
	public static boolean valid(String signature,String timestamp,String nonce,String echostr,String token) {
		
		if(signature==null||timestamp==null||nonce==null||echostr==null||token==null){
			return false;
		}
		
  		String mySignature = SecurityAlgorithm.encryptBySHA1(appendParams(timestamp, nonce, token));
  			
  		return mySignature.equals(signature);
  			
  	
	}
	
	private static String appendParams(String timestamp,String nonce,String token) {
		TreeMap<String, String> treeMap = new TreeMap<String, String>();


		treeMap.put(timestamp, "");
		treeMap.put(nonce, "");
		treeMap.put(token, "");

		StringBuffer result = new StringBuffer();
		Iterator<String> it = treeMap.keySet().iterator();

		while (it.hasNext()) {
			result.append(it.next());
		}
		
		return result.toString();
	}
}
